package com.guhappy.action;

import java.util.Map;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import nl.captcha.Captcha;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.SessionAware;

import com.guhappy.model.user.WebUser;
import com.guhappy.model.user.WebUserHome;
import com.guhappy.util.GenerateLinkUtils;
import com.opensymphony.xwork2.ActionSupport;


@ParentPackage("default")
@InterceptorRef("auditInterceptorStack")
public class SignupAction extends ActionSupport implements SessionAware {
    
	private static final long serialVersionUID = 1L;

    private Map<String, Object> session;
	
    private static final Logger logger = Logger
			.getLogger(UserLoginAction.class);
	
	private String username;

	private String password;

	private String repassword;

	private String email;

	private String captchaAnswer;
	
    public String getCaptchaAnswer() {
		return captchaAnswer;
	}
	public void setCaptchaAnswer(String captchaAnswer) {
		this.captchaAnswer = captchaAnswer;
	}
	public void setSession(Map<String, Object> session) {
        this.session = session;
    }
	@Action(value= "signupAction" ,results={
			@Result(name="success",location="/pages/registOk.jsp"),
			@Result(name="input",location="/pages/register.jsp")
			})
	public String execute() throws Exception {
		System.out.println("Regist invoked");
		if (WebUserHome.isExistUser(email)){
			this.addActionError(getText("user_already_exist"));
			return INPUT;
		}else{
		WebUser user = new WebUser();
		user.setEmail(email);
		user.setUserName(username);
		user.setStatus("0");
		user.setUserPassword(password);

		user.setUserHash(GenerateLinkUtils.HashPassword(password));
		user.setCodeCheck(GenerateLinkUtils.generateCheckcode(user));
		WebUserHome.attachDirty(user);

		String host = "smtp.gmail.com";
		String from = "bduan2";
		String pass = "20100101";
		Properties props = System.getProperties();
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.user", from);
		props.put("mail.smtp.password", pass);
		props.put("mail.smtp.port", "587");
		props.put("mail.smtp.auth", "true");

		Session session = Session.getDefaultInstance(props, null);
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(from));
		InternetAddress toAddress = new InternetAddress(email);
		System.out.println(Message.RecipientType.TO);
		System.out.println(toAddress.toString());
		message.addRecipient(Message.RecipientType.TO, toAddress);
		message.setSubject("Activate Email from GuHappy");
		message.setContent(getText("regist.welcome1") + "<a href='"
				+ GenerateLinkUtils.generateActivateLink(user)
				+ getText("regist.welcome2"), "text/html;charset=utf-8");
		Transport transport = session.getTransport("smtp");
		transport.connect(host, from, pass);
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
		return SUCCESS;}
	}
	
	 @Override
	    public void validate() {
	        Captcha captcha = (Captcha) session.get(Captcha.NAME);

	        if(!captcha.isCorrect(getCaptchaAnswer())) {
	            addFieldError("captchaAnswer", "not right!");
	        }
	    }

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	/*
	 * public String getCode() { return code; }
	 */

	public String getRepassword() {
		return repassword;
	}

	public void setRepassword(String repassword) {
		this.repassword = repassword;
	}

	/*
	 * public void setCode(String code) { this.code = code; }
	 */

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}
}
